<template>
  <FormItem :label="label" :single="single" :prop="prop">
    <input
      v-show="false"
      :disabled="isLoading"
      ref="inputFile"
      type="file"
      :accept="accept"
      @change="add($event)"
      :multiple="multiple"
    />
    <div class="h-input-group">
      <div class="h-input h-input-suffix-icon">
        <input
          type="text"
          :name="name"
          :value="cValue"
          :disabled="see"
          @input="updateVal($event.target.value)"
        />
        <i
          class="h-icon-upload"
          @click="fileChange"
          v-show="!see"
          style="cursor:pointer;padding-right:5px;"
        ></i>
      </div>
      <h-button
        color="blue"
        icon="h-icon-completed"
        :loading="isLoading"
        @click="confirm"
        :disabled="file.length <= 0"
      >上传</h-button>
    </div>
  </FormItem>
</template>
<script>
export default {
  props: {
    url: "",
    accept: "",
    multiple: {
      default: false
    },
    show: {
      default: true
    },
    name: {
      default: "file"
    },
    single: {
      default: false
    },
    params: {
      default: null
    },
    success: {
      default: "success"
    },
    value: "",

    label: "",
    prop: ""
  },
  data() {
    return {
      cValue: this.value,
      isLoading: false,
      file: [],
      message: ""
    };
  },
  computed: {
    see() {
      return this.$store.state.forms.see;
    }
  },
  methods: {
    fileChange() {
      this.$refs.inputFile.click();
    },
    add(event) {
      this.file = event.target.files;
      var names = new Array();
      for (var i = 0; i < this.file.length; i++) {
        names.push(this.file[i].name);
      }
      this.cValue = names.join(",");
    },
    confirm(event) {
      event.preventDefault();
      this.isLoading = true;
      let formData = new FormData();
      for (var i = 0; i < this.file.length; i++) {
        formData.append(this.name, this.file[i]);
      }
      if (!!this.params) {
        for (var key in this.params) {
          formData.append(key, this.params[key] || "");
        }
      }
      this.$axios(this.url, {
        method: "post",
        timeout: 60 * 1000 * 10,
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
        .then(res => {
          this.isLoading = false;
          if (res.data.code == "66666") {
            this.$Message.info("上传成功");
            this.file = [];
            this.cValue = res.data.msg;
            this.$emit("input", this.cValue);
            this.$bus.$emit(this.success, res.data.msg);
          } else {
            this.$Message.error(res.data.msg);
          }
        })
        .catch(err => {
          this.isLoading = false;
          this.$Message.error(err);
        });
    },
    updateVal(data) {
      this.$emit("input", data);
    }
  }
};
</script>